package com.github.icloudpay.pay.core.service.refund.alipay.service;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.github.icloudpay.pay.core.feign.PayChannelConfigFeign;
import com.github.icloudpay.pay.core.inter.QueryRefundStatusService;
import com.github.wxiaoqi.security.common.admin.pay.request.QueryRefundStatusRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.QueryRefundStatusResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * 支付宝退款订单查询
 * @author hexufeng
 *
 */
@Service("alipayQueryRefundStatusService")
public class AlipayQueryRefundStatusService implements QueryRefundStatusService {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(AlipayQueryRefundStatusService.class);

	@Autowired
	private PayChannelConfigFeign payChannelConfigFeign;

	@Override
	public QueryRefundStatusResponse queryRefundStatus(QueryRefundStatusRequest request) {

		logger.info("****************调用支付宝退款订单查询接口开始*******************");

		QueryRefundStatusResponse refundStatusResponse = new QueryRefundStatusResponse();

		Map<String, Object> reqMap = new HashMap<String, Object>();
    	reqMap.put("platformId", request.getPlatformId());
    	reqMap.put("merchantId", request.getMerId());
    	reqMap.put("payChannelNo", request.getPayChannelNo());
		Map<String, Object> respMap = payChannelConfigFeign.query(reqMap);
        if(!(boolean) respMap.get("success")){
			refundStatusResponse.setSuccess(false);
			refundStatusResponse.setCode(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			refundStatusResponse.setMsg(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return refundStatusResponse;
		}
        
        @SuppressWarnings("unchecked")
		Map<String, Object> configMap = (Map<String, Object>)respMap.get("payChannelConfigInfo");

		JSONObject json = new JSONObject();
		json.put("out_trade_no", request.getOutTradeNo());//支付订单号
		json.put("out_request_no ", request.getMchtRefundOrderNo());//退款请求号
		String jsonStr = json.toString();
		logger.info("调用支付宝请求参数。。。。。。。{}", jsonStr);

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",(String)configMap.get("outMerNo"),(String)configMap.get("outMerPrivateKey"),"json","UTF-8",(String)configMap.get("outMerPublicKey"),"RSA2");
		AlipayTradeFastpayRefundQueryRequest refundQueryRequest = new AlipayTradeFastpayRefundQueryRequest();
		refundQueryRequest.setBizContent(jsonStr);
		AlipayTradeFastpayRefundQueryResponse response;
		try {
			response = alipayClient.execute(refundQueryRequest);
			logger.info("调用支付宝响应参数。。。。。。。{}", EntityUtils.beanToMap(response));
			if(response.isSuccess() && "10000".equals(response.getCode())){
				if("REFUND_SUCCESS".equals(refundStatusResponse.getRefundStatus())){
					//成功
					refundStatusResponse.setResJrnNo(response.getTradeNo());
					refundStatusResponse.setOutTradeNo(response.getOutTradeNo());
					refundStatusResponse.setRefundFee(response.getRefundAmount());
					refundStatusResponse.setRefundStatus("00");//退款成功
				}else if("REFUND_PROCESSING".equals(refundStatusResponse.getRefundStatus())){
					refundStatusResponse.setRefundStatus("02");//退款处理中
				}else{
					//失败
					refundStatusResponse.setRefundStatus("01");//退款失败
				}
				refundStatusResponse.setSuccess(true);
				refundStatusResponse.setCode(ResponseCode.OK.getCode());
	            refundStatusResponse.setMsg(ResponseCode.OK.getMessage());
			} else {
				refundStatusResponse.setSuccess(false);
				refundStatusResponse.setCode(ResponseCode.SEND_DATA_FAIL.getCode());
				refundStatusResponse.setMsg(ResponseCode.SEND_DATA_FAIL.getMessage());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return refundStatusResponse;
	}
}